<template>
  <div class="chatView">
    <Header
      :title="targetUser.name"
      :is-left="true"
      v-if="targetUser"
      btn_icon="ellipsis-h"
    ></Header>
    <transition name="fade">
      <div class="container"  v-if="targetUser && user" >
        <!-- 聊天内容 -->
        <!-- 判断本人的信息和router传过来的信息都必须要有,证明是正常状态,如果都不空的话就遍历 -->
        <div class="content_wrap"  v-for="(item,index) in messageList"   :key="index" >
          <!-- 对方的聊天内容 -->
            <div class="left_msg" v-if="item.source == 'other'">
              <img :src="targetUser.avatar" alt="">
              <span>{{item.msg}}</span>
            </div>
          <!-- 我的聊天内容 -->
            <div class="right_msg" v-if="item.source == 'self'">
                <span>{{item.msg}}</span>
                <img :src="user.avatar" alt="">
              </div>
        </div>
      </div>
    </transition> 
    <!-- 信息输入框 -->
    <div class="footer_wrap">
      <input
        type="text"
        v-model="msgValue"
      >
      <button
        :disabled="msgValue == ''"
        @click="sendMessage"
      >发送</button>

    </div>
  </div>
</template>
<script>
import Header from "../components/Header";
import WSocket from '../socket.js'
export default {
  name: "chatView",
  components: {
    Header
  },
  data() {
    return {
      targetUser: null,
      msgValue: "",
      messageList:[],//用户信息列表 
    };
  },
  computed:{
    user(){
      // 点击进来获取本人的信息
      return this.$store.getters.user
    }
  },
  mounted(){//服务端推送过来的消息
    /**
     *  页面一开始的时候加载websocket方法;
     * 分别放三个参数;第一个为用户,把传入的本人信息id录入
     * 二为,消息,message,把获取到的消息存入this.messageList渲染
     * 三为,错误 
     *  */
    WSocket.init({user:this.user},message=>{
      //收到消息后,存入数组
      this.messageList.push({
        msg:message.msg,
        source:'other',//接收到的是对方传入的消息
      });
      // 保存消息
      this.saveMsg()
    },error =>{
      console.log(error)
    });
  },
  methods: {
    sendMessage() {//发送消息
      console.log(this.msgValue);
      const msgObj = {
        target:this.targetUser._id,//传入对方的ID去到服务器
        current:this.user.id,//本人的ID
        msg:this.msgValue,//把输入框的数据传去服务器

      };
      // 把对象放入socket
      WSocket.send(msgObj);
      // 本地客户端在对话框中显示内容
      this.messageList.push({
        msg:this.msgValue,
        source:'self',
      });
      // 保存当前的消息
      this.saveMsg()
      // 清空inPut
      this.msgValue = '';
    },
    // 保存对话框中的聊天记录
    saveMsg(){
      // 定义消息
      let message = {
        target:{
          avatar:this.targetUser.avatar,
          name:this.targetUser.name,
          _id:this.targetUser._id
        },
        count:0,//定义没有发消息的时候为0
        message:this.messageList,
        user_id:this.user.id
      }
      this.$axios.post('/api/profile/addmsg',message).then(res=>{
        this.msgValue = ''
      })
    },
    getMessage(){
      // 请求聊天对象的信息ID
      this.$axios.get(`/api/profile/msg/${this.user.id}`).then(res=>{
        console.log(res.data)
        // 过滤与当前目标对象的聊天数据 
        let result = res.data.filter(data =>{
            // data.target._id 如进来是张三,那把张三的id与上一个页面传过来用户的ID进行对比
            return data.target._id == this.targetUser._id
          })
          // 对result进行判断;如果有长度;代表有数据 
         if(result.length > 0) {
           this.messageList = result[0].message;
         }

      })
    },
    // 滚动到底部
     scrollToBottom() {
     this.$nextTick(() => {
      var container = this.$el.querySelector('.container');
        container.scrollTop = container.scrollHeight;
     })}

  },
  created() {
  },
  updated(){
     this.scrollToBottom();
  },
  beforeCreate(){

    // console.log(JSON.parse(localStorage.getItem('user')))
    // console.log(JSON.parse(sessionStorage.getItem('users')))

  },
  beforeRouteEnter(to, from, next) {
    next(vm => {
      // vm.targetUser = JSON.parse(to.params.user)
      // 解码
      vm.targetUser =JSON.parse(decodeURI(to.query.user))
       vm.getMessage()
      // vm.targetUser =JSON.parse(to.query.user)
    });
  }
};
</script>
<style scoped>
.chatView {
  width: 100%;
  height: 100%;
  overflow: hidden;
}
.fade-enter-active, .fade-leave-active {
  transition: opacity 2s;
}
.fade-enter, .fade-leave-to /* .fade-leave-active below version 2.1.8 */ {
  opacity: 0;
}
.container {
  width: 100%;
  height: calc(100% - 100px);
  background: #f1f1f1;
  margin-top: 50px;
  padding: 8px;
  overflow-y: scroll;
}
.footer_wrap {
  width: 100%;
  height: 50px;
  border-top: 1px solid #d9d9d9;
  position: absolute;
  bottom: 0;
  padding: 8px;
  background-color: #fafafa;
}
.footer_wrap input {
  width: 70%;
  height: 30px;
  border: 1px solid #d9d9d9;
  border-radius: 4px;
  outline: none;
}
.footer_wrap button {
  width: 20%;
  height: 34px;
  border: 1px solid #d9d9d9;
  border-radius: 4px;
  margin-left: 8px;
  outline: none;
  background: #f1f1f1;
}
.footer_wrap button[disabled] {
  background: #d9d9d9;
  cursor: not-allowed;
  pointer-events: none;
}

/* 聊天样式 */
.right_msg span,.left_msg span{
  border: 1px solid #d9d9d9;
  border-radius: 4px;
  margin: 0 5px;
  padding: 8px;
  box-sizing: border-box;
  word-break: break-all;
}
.content_wrap{
  clear: both;
}
.left_msg{
margin-bottom: 20px;
}
.right_msg{
float: right;
margin-bottom: 20px;
}
.left_msg img,.right_msg img{
  width: 50px;
  height: 50px;
  border-radius: 5px;
  vertical-align: middle;
}
.left_msg span{
  background-color: #fff;
}
.right_msg span{
  background-color: #0fce0d;
}
</style>

